﻿@page "/Account/Manage/ResetAuthenticator"

@using Microsoft.AspNetCore.Identity
@using MudBlazor.Template.Data

@inject UserManager<ApplicationUser> UserManager
@inject SignInManager<ApplicationUser> SignInManager
@inject IdentityUserAccessor UserAccessor
@inject IdentityRedirectManager RedirectManager
@inject ILogger<ResetAuthenticator> Logger

<PageTitle>Reset authenticator key</PageTitle>

<MudText Typo="Typo.h6" GutterBottom="true">Reset authenticator key</MudText>

<StatusMessage />

<MudAlert Severity="Severity.Warning" Variant="Variant.Text">
    If you reset your authenticator key your authenticator app will not work until you reconfigure it.
</MudAlert>

<MudText Typo="Typo.body2" Class="my-4">
    This process disables 2FA until you verify your authenticator app.
    If you do not complete your authenticator app configuration you may lose access to your account.
</MudText>

<form @formname="reset-authenticator" @onsubmit="OnSubmitAsync" method="post">
    <AntiforgeryToken />

    <MudStaticButton Variant="Variant.Filled" Color="Color.Primary" FullWidth="true" FormAction="FormAction.Submit">Reset authenticator key</MudStaticButton>
</form>

@code {
    [CascadingParameter]
    private HttpContext HttpContext { get; set; } = default!;

    private async Task OnSubmitAsync()
    {
        var user = await UserAccessor.GetRequiredUserAsync(HttpContext);
        await UserManager.SetTwoFactorEnabledAsync(user, false);
        await UserManager.ResetAuthenticatorKeyAsync(user);
        var userId = await UserManager.GetUserIdAsync(user);
        Logger.LogInformation("User with ID '{UserId}' has reset their authentication app key.", userId);

        await SignInManager.RefreshSignInAsync(user);

        RedirectManager.RedirectToWithStatus(
            "Account/Manage/EnableAuthenticator",
            "Your authenticator app key has been reset, you will need to configure your authenticator app using the new key.",
            HttpContext);
    }
}
